package com.ruoyi.lxy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.lxy.domain.*;
import com.ruoyi.lxy.domain.bo.TSelectDependantBo;
import com.ruoyi.lxy.domain.vo.TRouteVo;
import com.ruoyi.lxy.domain.vo.TUserVo;
import com.ruoyi.lxy.mapper.*;
import com.ruoyi.lxy.zust.domain.TStaff;
import com.ruoyi.lxy.zust.service.impl.TStaffServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.ruoyi.lxy.domain.bo.TDependantBo;
import com.ruoyi.lxy.domain.vo.TDependantVo;
import com.ruoyi.lxy.service.ITDependantService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 家属Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-24
 */
@RequiredArgsConstructor
@Service
public class TDependantServiceImpl implements ITDependantService {

    private final TDependantMapper baseMapper;
    private final TSelectDependantServiceImpl tSelectDependantService;
    private final TStaffServiceImpl tStaffService;
    private final TTimeMapper timeMapper;
    private final TProjectMapper projectMapper  ;
    private final TRouteMapper routeMapper;
    private final TSelectDependantMapper tSelectDependantMapper;
    /**
     * 查询家属
     */
    @Override
    public TDependantVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询家属列表
     */
    @Override
    public TableDataInfo<TDependantVo> queryPageList(Long timeId, TDependantBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TDependant> lqw = buildQueryWrapper(bo);
        lqw.inSql(TDependant::getId,"select dependant_id from t_select_dependant where time_id= '"+timeId+"' and  del_flag=0 ");
        Page<TDependantVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询家属列表
     */
    @Override
    public List<TDependantVo> queryList(Long timeId) {
//        LambdaQueryWrapper<TDependant> lqw = Wrappers.lambdaQuery();
//        lqw.inSql(TDependant::getId,"select dependant_id from t_select_dependant where time_id= '"+timeId+"' and  del_flag=0 ");
//        List<TDependantVo> result=baseMapper.selectVoList(lqw);


        List<TDependant> tDependants = baseMapper.selectDependantListByTimeId(timeId);
        List<TDependantVo> tDependantVos = new ArrayList<>();
        for (int i=0;i<tDependants.size();i++){
            TDependantVo vo=new TDependantVo();
            BeanUtils.copyProperties(tDependants.get(i),vo);

            TUser tUser=baseMapper.selectUserByUserId(tDependants.get(i).getUserId());
            vo.setUserName(tStaffService.selectByZgh(tUser.getZgh()).getXM());

            tDependantVos.add(StateTransitionVo(vo));
        }
        return tDependantVos;
    }

    private TDependantVo StateTransitionVo(TDependantVo tDependantVo) {
        if(tDependantVo.getType()!=null){
            switch (tDependantVo.getType()){
                case 0:
                    tDependantVo.setTypeCode("成人");
                    break;
                case 1:
                    tDependantVo.setTypeCode("儿童");
                    break;
                case 2:
                    tDependantVo.setTypeCode("老人");
                    break;
            }
        }

        if(tDependantVo.getNeedBed()!=null){
            switch (tDependantVo.getNeedBed()){
                case 0:
                    tDependantVo.setNeedBedCode("不需要");
                    break;
                case 1:
                    tDependantVo.setNeedBedCode("需要");
                    break;
            }
        }

        return tDependantVo;
    }

    private LambdaQueryWrapper<TDependant> buildQueryWrapper(TDependantBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TDependant> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, TDependant::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), TDependant::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), TDependant::getGender, bo.getGender());
        lqw.eq(bo.getType() != null, TDependant::getType, bo.getType());
        lqw.eq(bo.getHeight() != null, TDependant::getHeight, bo.getHeight());
        lqw.eq(bo.getNeedBed() != null, TDependant::getNeedBed, bo.getNeedBed());
        lqw.eq(bo.getAge() != null, TDependant::getAge, bo.getAge());
        return lqw;
    }

    /**
     * 新增家属
     */
    @Override
    public Boolean insertByBo(TDependantBo bo) {
        //查找当前时间段中家属选择表的家属id
        LambdaQueryWrapper<TSelectDependant> lqw2 = Wrappers.lambdaQuery();
        lqw2.eq(TSelectDependant::getTimeId, bo.getTimeId());
        List<Long> dependantIds = tSelectDependantMapper.selectList(lqw2).stream()
            .map(TSelectDependant::getDependantId).collect(Collectors.toList());
        //查询家属表中用户id与家属id相同的家属数量
        //计算表中dependantIds相同的数量
        int count = 0;
        for (Long dependantId : dependantIds) {
            LambdaQueryWrapper<TDependant> lqw = Wrappers.lambdaQuery();
            lqw.eq(TDependant::getUserId, dependantId);
            if (baseMapper.selectCount(lqw)>0) {
                count++;
            }
        }

        LambdaQueryWrapper<TDependant> lqw1 = Wrappers.lambdaQuery();
        lqw1.eq(TDependant::getUserId, bo.getUserId());
        TTime tTime = timeMapper.selectById(bo.getTimeId());
        TRoute tRoute = routeMapper.selectById(tTime.getRouteId());
        TProject tProject = projectMapper.selectById(tRoute.getProjectId());
        if(tRoute.getCanBringCode()==1) {
            throw new RuntimeException("该路线不允许携带家属");
        }else if(tRoute.getCanBringCode()==0){
            //当前项目家属人数上限
            if(tProject.getBringdepeMax()!=null&&tProject.getBringdepeMax()!=0){
                lqw1.eq(TDependant::getDelFlag, 0);
                if (count >= tProject.getBringdepeMax()) {
                    throw new RuntimeException("该项目家属人数已满");
                }
            }
            if(tTime.getStaffCount()>=tTime.getStaffMax()){
                throw new RuntimeException("该路线总人数已满");
            }
        }

        TDependant add = BeanUtil.toBean(bo, TDependant.class);
        validEntityBeforeSave(add);
        TSelectDependantBo tSelectDependantBo = new TSelectDependantBo();
        tSelectDependantBo.setTimeId(bo.getTimeId());
        boolean flag = baseMapper.insert(add) > 0;

        if (flag) {
            bo.setId(add.getId());
        }
        //查询家属id
        LambdaQueryWrapper<TDependant> lqw = buildQueryWrapper(bo);
        lqw.eq(bo.getIdcard() != null, TDependant::getIdcard, bo.getIdcard());
        TDependant tDependant = baseMapper.selectOne(lqw);
        tSelectDependantBo.setDependantId(tDependant.getId());
        tSelectDependantService.insertByBo(tSelectDependantBo);
        return flag;
    }

    /**
     * 修改家属
     */
    @Override
    public Boolean updateByBo(TDependantBo bo) {
        TDependant update = BeanUtil.toBean(bo, TDependant.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TDependant entity) {
        //TODO 做一些数据校验,如唯一约束


    }

    /**
     * 批量删除家属
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }

        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 删除家属
     */
    @Override
    public boolean deleteWithValidById(Collection<Long> ids, long timeId, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (Long id : ids) {
            tSelectDependantService.deleteWithValidById(id, timeId, isValid);
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<TDependantVo> selectDependantListByTimeId(Long timeId,TDependantBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<TDependant> lqw = buildQueryWrapper(bo);
//        lqw.inSql(TDependant::getId,"select dependant_id from t_select_dependant where time_id= '"+timeId+"' and  del_flag=0 ");
//        Page<TDependantVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        List<TDependant> tDependants = baseMapper.selectDependantListByTimeId(timeId);
        List<TDependant> tDependants = baseMapper.selectDependantList(timeId,bo);
        List<TDependantVo> tDependantVos = new ArrayList<>();
        for (int i=0;i<tDependants.size();i++){
            TDependantVo vo=new TDependantVo();
            BeanUtils.copyProperties(tDependants.get(i),vo);

            TUser tUser=baseMapper.selectUserByUserId(tDependants.get(i).getUserId());
            vo.setUserName(tStaffService.selectByZgh(tUser.getZgh()).getXM());

            tDependantVos.add(vo);


        }
        return TableDataInfo.build(tDependantVos);



    }
    //删除
}
